<template>
  <div id="app">
    <router-view></router-view>
    <div v-if="showPopup" class="popup">
      <div class="custom-van-result">
        <img :src="iconUrl" alt="自定义图标" class="custom-icon"><br>
        <div class="van-result-content">
          <div class="van-result-title">{{ reminder.name }}</div>
          <div class="van-result-tip">{{ '吃药时间到了' }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {remind} from './views/index/remind/remind';

export default {
  data() {
    return {
      showPopup: false,
      reminder: null,
      iconUrl: 'http://srhtngjmu.hn-bkt.clouddn.com/index/%E4%B9%96%E5%90%83%E8%8D%AF.png?e=1739274428&token=rWxRhgEIi6r6WpeIwlvhTEPMnsDCB8KqZ34tVS7A:fgnCuMeBg2IQwPG_uBoflZF63K0=',
      intervalId: null,
      lastCheckedMinute: null,
      reminders: []
    };
  },
  mounted() {
    this.fetchReminders();
    this.startChecking();
    remind.$on('showPopup', payload => {
      console.log('Received showPopup event');
      this.showPopup = true;
      this.reminder = payload.reminder;
    });
    remind.$on('hidePopup', () => {
      console.log('Received hidePopup event');
      this.showPopup = false;
    });
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
    remind.$off('showPopup');
    remind.$off('hidePopup');
  },
  methods: {
    fetchReminders() {
      // 这里可以从本地存储、API等获取提醒数据
      // 暂时假设reminders数据从本地存储获取
      const storedReminders = localStorage.getItem('reminders');
      if (storedReminders) {
        this.reminders = JSON.parse(storedReminders);
        console.log('Fetched reminders:', this.reminders);
      }
    },
    startChecking() {
      this.intervalId = setInterval(() => {
        const now = new Date();
        const currentMinute = now.getMinutes();
        if (this.lastCheckedMinute === null || currentMinute !== this.lastCheckedMinute) {
          this.lastCheckedMinute = currentMinute;
          this.reminders.forEach(reminder => {
            this.checkReminder(reminder);
          });
        }
      }, 1000);
    },
    checkReminder(reminder) {
      if (reminder.isEnabled) {
        const now = new Date();
        const currentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
        console.log('Current time:', currentTime);
        if (reminder.reminderDays.includes("每天")) {
          reminder.medicationTime.forEach(time => {
            console.log('Checking time:', time);
            if (time === currentTime && (!reminder.lastReminded || reminder.lastReminded < now)) {
              console.log("提醒：" + reminder.drugName + " " + reminder.medicationTime[0]);
              remind.$emit('showPopup', {reminder});
              reminder.lastReminded = now;
              setTimeout(() => {
                remind.$emit('hidePopup');
              }, 5000);
            }
          });
        } else if (reminder.reminderDays.includes("每隔一天")) {
          const targetTime = new Date();
          targetTime.setHours(parseInt(reminder.medicationTime[0].split(':')[0]));
          targetTime.setMinutes(parseInt(reminder.medicationTime[0].split(':')[1]));
          const currentDay = now.getDate();
          const targetDay = targetTime.getDate();
          console.log('Current day:', currentDay, 'Target day:', targetDay);
          if ((currentDay - targetDay) % 2 === 0 && targetTime >= now && (!reminder.lastReminded || reminder.lastReminded < now)) {
            console.log("提醒：" + reminder.drugName + " " + reminder.medicationTime[0]);
            remind.$emit('showPopup', {reminder});
            reminder.lastReminded = now;
            setTimeout(() => {
              remind.$emit('hidePopup');
            }, 5000);
          }
        }
      }
    }
  }
};
</script>

<style scoped>
.popup {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  z-index: 1000;
  text-align: center;
}

.custom-van-result {
}

.custom-icon {
  width: 130px;
  height: 100px;
  margin-right: 10px;
}

.van-result-content {
  display: flex;
  flex-direction: column;
}

.van-result-title {
  font-size: 18px;
  font-weight: bold;
}

.van-result-tip {
  font-size: 14px;
  color: #666;
}
</style>